package com.cmc.cloud.cmclink.doc.service.impl.si;

import com.cmc.cloud.cmclink.doc.api.document.rep.BlnoPageRespDto;
import com.cmc.cloud.cmclink.doc.constant.DocApiConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoSpiltCombineDetailErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.entity.BlnoDO;
import com.cmc.cloud.cmclink.doc.entity.BlnoSpiltCombineDO;
import com.cmc.cloud.cmclink.doc.entity.ConfirmNoticeDO;
import com.cmc.cloud.cmclink.doc.mapper.BlnoMapper;
import com.cmc.cloud.cmclink.doc.mapper.BlnoSpiltCombineMapper;
import com.cmc.cloud.cmclink.doc.mapper.ConfirmNoticeMapper;
import com.cmc.cloud.cmclink.doc.service.si.BlnoSpiltCombineDetailService;
import com.cmc.cloud.cmclink.doc.api.document.rep.blnospiltcombinedetailvo.BlnoSpiltCombineDetailCreateReqVO;
import com.cmc.cloud.cmclink.doc.api.document.rep.blnospiltcombinedetailvo.BlnoSpiltCombineDetailPageReqVO;
import com.cmc.cloud.cmclink.doc.api.document.rep.blnospiltcombinedetailvo.BlnoSpiltCombineDetailUpdateReqVO;
import com.cmes.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;

import java.util.*;
import com.cmc.cloud.cmclink.doc.entity.BlnoSpiltCombineDetailDO;
import com.cmc.cloud.cmclink.doc.convert.BlnoSpiltCombineDetailConvert;
import com.cmc.cloud.cmclink.doc.mapper.BlnoSpiltCombineDetailMapper;

/**
 * 提单拆并申请主 Service 实现类
 *
 * @author 集运管理员
 */
@Service
@Validated
public class BlnoSpiltCombineDetailServiceImpl implements BlnoSpiltCombineDetailService {


    @Resource
    private BlnoSpiltCombineDetailMapper blnoSpiltCombineDetailMapper;
    @Resource
    private BlnoSpiltCombineMapper blnoSpiltCombineMapper;
    @Resource
    private BlnoMapper blnoMapper;
    @Resource
    private ConfirmNoticeMapper confirmNoticeMapper;

    @Override
    public void createBlnoSpiltCombineDetail(BlnoSpiltCombineDetailCreateReqVO createReqVO) {
        // 插入
        BlnoSpiltCombineDetailDO blnoSpiltCombineDetail = BlnoSpiltCombineDetailConvert.INSTANCE.convert(createReqVO);
        blnoSpiltCombineDetailMapper.insert(blnoSpiltCombineDetail);
    }

    @Override
    public void updateBlnoSpiltCombineDetail(BlnoSpiltCombineDetailUpdateReqVO updateReqVO) {
        // 校验存在
        validateBlnoSpiltCombineDetailExists(updateReqVO.getId());
        // 更新
        BlnoSpiltCombineDetailDO updateObj = BlnoSpiltCombineDetailConvert.INSTANCE.convert(updateReqVO);
        blnoSpiltCombineDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteBlnoSpiltCombineDetail(Long id) {
        // 校验存在
        validateBlnoSpiltCombineDetailExists(id);
        // 删除
        blnoSpiltCombineDetailMapper.deleteById(id);
    }

    private void validateBlnoSpiltCombineDetailExists(Long id) {
        if (blnoSpiltCombineDetailMapper.selectById(id) == null) {
            throw ServiceExceptionUtil
                .exception(BlnoSpiltCombineDetailErrorCodeConstants.BLNO_SPILT_COMBINE_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public BlnoSpiltCombineDetailDO getBlnoSpiltCombineDetail(Long id) {
        return blnoSpiltCombineDetailMapper.selectById(id);
    }

    @Override
    public List<BlnoSpiltCombineDetailDO> getBlnoSpiltCombineDetailList(Collection<Long> ids) {
        return blnoSpiltCombineDetailMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlnoSpiltCombineDetailDO> getBlnoSpiltCombineDetailPage(BlnoSpiltCombineDetailPageReqVO reqVO) {
        IPage<BlnoSpiltCombineDetailDO> page = Page.of(reqVO.getPageNo(), reqVO.getPageSize());

        IPage<BlnoSpiltCombineDetailDO> result = blnoSpiltCombineDetailMapper.selectPageList(page, reqVO);
        return new PageResult<BlnoSpiltCombineDetailDO>(result.getRecords(), result.getTotal());
    }

    @Override
    public BlnoSpiltCombineDO getSpiltCombineAudit(BlnoPageRespDto dto) {
        Long blnoId = dto.getBlnoId();
        dto.setBlShipperChangeFlag(false);
        if(blnoId == null){
            return null;
        }
        // 拆并详情表数据 取最新的那条
        LambdaQueryWrapper<BlnoSpiltCombineDetailDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlnoSpiltCombineDetailDO::getBlnoId, blnoId)
                .orderByDesc(BlnoSpiltCombineDetailDO::getUpdateTime)
                .last("limit 1");
        BlnoSpiltCombineDetailDO detailDO = blnoSpiltCombineDetailMapper.selectOne(wrapper);
        //查询是否存在更正流程
        BlnoDO newBlnoDo = blnoMapper.selectOne(new LambdaQueryWrapperX<BlnoDO>().eq(BlnoDO::getOldBlnoId, blnoId)
                .orderByDesc(BlnoDO::getCreateTime)
                .last("limit 1"));
        BlnoSpiltCombineDO blnoSpiltCombine=new BlnoSpiltCombineDO();
        if (Objects.nonNull(detailDO)) {
            blnoSpiltCombine = blnoSpiltCombineMapper.selectById(detailDO.getOperationId());
            if (Objects.isNull(newBlnoDo)) {
                return blnoSpiltCombine;
            }
            ConfirmNoticeDO confirmNotice = confirmNoticeMapper.selectOne(new LambdaQueryWrapperX<ConfirmNoticeDO>().eq(ConfirmNoticeDO::getBlnoId, newBlnoDo.getId()).last("limit 1"));
            if (Objects.isNull(confirmNotice)) {
                return blnoSpiltCombine;
            }
            if (blnoSpiltCombine.getUpdateTime().isBefore(confirmNotice.getUpdateTime())) {
                blnoSpiltCombine.setUpdateTime(confirmNotice.getUpdateTime());
                blnoSpiltCombine.setOperationType(DocApiConstants.SI_CHANGE_TYPE);
                blnoSpiltCombine.setApproveStatus(confirmNotice.getStatus());
                dto.setBlShipperChangeFlag(this.getBlShipperChangeFlag(newBlnoDo,dto));
            }
            return blnoSpiltCombine;
        }
        if (Objects.nonNull(newBlnoDo)){
            ConfirmNoticeDO confirmNotice = confirmNoticeMapper.selectOne(new LambdaQueryWrapperX<ConfirmNoticeDO>().eq(ConfirmNoticeDO::getBlnoId, newBlnoDo.getId()).last("limit 1"));
            if (Objects.isNull(confirmNotice)) {
                return blnoSpiltCombine;
            }
            blnoSpiltCombine.setUpdateTime(confirmNotice.getUpdateTime());
            blnoSpiltCombine.setOperationType(DocApiConstants.SI_CHANGE_TYPE);
            blnoSpiltCombine.setApproveStatus(confirmNotice.getStatus());
            dto.setBlShipperChangeFlag(this.getBlShipperChangeFlag(newBlnoDo,dto));
        }
        // 查询操作表日志
        return blnoSpiltCombine;
    }

    /**
     * 设置船期修改flag
     * @param newBlnoDo
     * @param dto
     * @return
     */
    private boolean getBlShipperChangeFlag(BlnoDO newBlnoDo,BlnoPageRespDto dto){
        if(!Objects.equals(newBlnoDo.getPorCode(),dto.getPorCode())
                || !Objects.equals(newBlnoDo.getPolCode(),dto.getPolCode())
                || !Objects.equals(newBlnoDo.getPodCode(),dto.getPodCode())
                || !Objects.equals(newBlnoDo.getDelCode(),dto.getDelCode())
                || !Objects.equals(newBlnoDo.getBkgVoyage(),dto.getVoyage())
                || !Objects.equals(newBlnoDo.getBkgVesselCode(),dto.getVesselCode())) {
            return true;
        }
        return false;
    }
}
